<template>
  <div>
    <en-table-layout
      toolbar
      pagination
      :tableData="tableData"
      :loading="loading"
      :selection-change="handleSelectionChange">
      <div slot="toolbar" class="inner-toolbar">
        <div class="toolbar-btns">
          <el-button type="primary" @click="handleAddCoupon">新增</el-button>
          <el-button type="primary" @click="handlePushToClient">推送到用户</el-button>
        </div>
        <div class="toolbar-search">
          <div class="cityAddr">
            <span>
              优惠券类型:
            </span>
            <el-select v-model="searchCouponData" size="small" clearable filterable placeholder="请选择优惠券类型" @change="searchCoupon_type">
              <el-option label="商品券" value="GOODS"></el-option>
              <el-option label="新人券" value="NEW_REG"></el-option>
              <el-option label="地推券" value="MARKET"></el-option>
              <el-option label="售后券" value="AFTERSALE"></el-option>
              <el-option label="红包券" value="RED_COUPON"></el-option>
              <el-option label="首单劵" value="FIRST_ORDER"></el-option>
              <el-option label="营销券" value="MARKETING_VOUCHER"></el-option>
              <el-option label="拉新券" value="PULL_NEW"></el-option>
            </el-select>
          </div>
          <en-table-search
            @search="searchEvent"
            @advancedSearch="advancedSearchEvent"
            advancedWidth="465"
            advanced
            placeholder="请输入关键字">
            <template slot="advanced-content">
              <el-form ref="advancedForm" :model="advancedForm" label-width="80px">
                <el-form-item label="有效期">
                  <el-date-picker
                    v-model="advancedForm.coupon_time_limit"
                    type="daterange"
                    align="center"
                    range-separator="-"
                    value-format="timestamp"
                    :default-time="['00:00:00', '23:59:59']"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期">
                  </el-date-picker>
                </el-form-item>
              </el-form>
            </template>
          </en-table-search>
        </div>
      </div>
      <template slot="table-columns">
        <el-table-column type="selection" width="47"/>
        <el-table-column prop="coupon_id" label="优惠券ID" width="80"/>
        <el-table-column prop="title" label="优惠券名称" width="180"/>
        <el-table-column prop="coupon_price" label="优惠券面额（元）" width="80" />
        <el-table-column prop="coupon_threshold_price" label="使用限制(元)" width="80" />
        <el-table-column label="领取期限" width="240">
          <template slot-scope="scope">
            {{ scope.row.start_time | unixToDate('yyyy-MM-dd') }}~
            {{ scope.row.end_time | unixToDate('yyyy-MM-dd') }}
          </template>
        </el-table-column>
        <el-table-column label="使用期限" width="260">
          <template slot-scope="scope">
            <div v-if="scope.row.use_start_time">
              {{ scope.row.use_start_time | unixToDate('yyyy-MM-dd hh:mm:ss')}} - {{scope.row.use_end_time | unixToDate('yyyy-MM-dd hh:mm:ss') }}
            </div>
            <div v-else-if="scope.row.use_period !== null">
              {{scope.row.use_period}}天
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="coupon_type" label="优惠券类型" width="120" >
          <template slot-scope="scope">
            {{ scope.row.coupon_type | couponTypeFilter }}
          </template>
        </el-table-column>
        <el-table-column prop="create_num" label="发行量（个）" width="120" />
        <el-table-column prop="received_num" label="已领取量（个）" width="120" />
        <el-table-column prop="used_num" label="已使用量（个）" width="120"/>
        <el-table-column label="操作" min-width="270">
          <template slot-scope="scope">
            <el-button
              type="success"
              @click="handleEditCoupons(scope.row)">修改
            </el-button>
            <el-button
              type="warning"
              :disabled="scope.row.end_time < parseInt(new Date().getTime()/1000)"
              @click="handleEndCoupons(scope.row)">结束
            </el-button>
            <el-button
              type="danger"
              @click="handleDeleteGoods(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </template>
      <el-pagination
        slot="pagination"
        v-if="pageData"
        @size-change="handlePageSizeChange"
        @current-change="handlePageCurrentChange"
        :current-page="pageData.page_no"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageData.page_size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageData.data_total">
      </el-pagination>
    </en-table-layout>
    <!--优惠券组件-->
    <Coupon
      :couponModelShow="couponModelShow"
      :currentcouponId="currentcouponId"
      @saveCoupon="saveCoupon"
    ></Coupon>

    <!--推送到用户 dialog-->
    <el-dialog title="推送到用户" :close-on-press-escape="false"
      :visible.sync="dialogPushShow" width="750px" :close-on-click-modal="false" >
      <el-form :model="pushForm" :rules="pushRules" ref="pushForm" label-width="100px">
        <!-- <p class="choosedPromos">
          已选中：{{selectedPromos.title}} - {{selectedPromos.coupon_type | couponTypeFilter }} - {{selectedPromos.coupon_price}}元
        </p> -->
        <el-form-item label="已选中：" class="choosedPromos">
          <span>{{selectedPromos.count}}个优惠券，共{{selectedPromos.pice }}张进行推送</span>
        </el-form-item>
        <el-form-item label="推送用户：" prop="mobile" required>
          <el-input type="textarea"  v-model="pushForm.mobile" placeholder="请输入用户手机号，多个用户用逗号“，”分隔" clearable></el-input>
        </el-form-item>
        <el-form-item label="短信通知：" prop="content">
          <el-input type="textarea"  v-model="pushForm.content" clearable></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogPushShow = false">取 消</el-button>
        <el-button type="primary" @click="submitpushForm('pushForm')" :loading="btnLoading">确认推送</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import * as API_coupon from '@/api/coupon'
  import { CategoryPicker } from '@/components'
  import { Coupon, batch_push } from './components'
  export default {
    name: 'discountManager',
    components: {
      [CategoryPicker.name]: CategoryPicker,
      [Coupon.name]: Coupon
    },
    data() {
      return {
        /** 列表loading状态 */
        loading: false,
        /** 推送按钮loading状态 */
        btnLoading: false,

        /** 列表参数 */
        params: {
          page_no: 1,
          page_size: 10
        },

        /** 列表数据 */
        tableData: null,

        /** 列表分页数据 */
        pageData: null,

        /** 高级搜索数据 */
        advancedForm: {
          coupon_time_limit: []
        },

        /** 优惠券弹框显示*/
        couponModelShow: false,

        /** 被选数据 */
        selectedData: [],

        /** 被选优惠券 */
        selectedPromos: {
          count: '',
          count_price: '',
          pice: ''
        },

        /** 推送优惠券弹框显示*/
        dialogPushShow: false,
        /** 推送 表单 */
        pushForm: {
          mobile: '',
          content: ''
        },
        /** 添加团购 表单规则 */
        pushRules: {
          mobile: [
            { required: true, message: '用户手机号不能为空', trigger: 'blur' },
            { pattern: /^[0-9,，,.\n]+$/, message: '请输入正确的用户手机号，多个用户用逗号“，”分隔', trigger: 'blur' }
          ]
        },

        /** 当前优惠券ID*/
        currentcouponId: '',

        /** 优惠券表单*/
        couponModelForm: {
          /** 优惠券名称*/
          title: '',

          /** 优惠券面额（元）*/
          coupon_price: 2,

          /** 使用限制（元）*/
          coupon_threshold_price: 2,

          /** 使用时限 */
          coupon_time_limit: '2017-02-25',

          /** 发行量（个） */
          create_num: 2,

          /** 已使用量（个） */
          used_num: 2
        },
        /** 优惠券类型 */
        searchCouponData: ''
      }
    },
    mounted() {
      this.GET_CouponsList();
    },
    filters: {
      couponTypeFilter(val) {
        let _back = '';
        switch (val) {
          case 'GOODS':
            _back='商品券';
            break;
          case 'NEW_REG':
            _back='新人券';
            break;
          case 'MARKET':
            _back='地推券';
            break;
          case 'AFTERSALE':
            _back='售后券';
            break;
          case 'RED_COUPON':
            _back='红包券';
            break;
          case 'FIRST_ORDER':
            _back='首单卷';
            break;
          case 'MARKETING_VOUCHER':
            _back='营销券';
            break;
          case 'PULL_NEW':
            _back='拉新券';
            break;
        }
        return _back;
      }
    },
    methods: {

      /** 分页大小发生改变 */
      handlePageSizeChange(size) {
        this.params.page_size = size
        this.GET_CouponsList()
      },

      /** 分页页数发生改变 */
      handlePageCurrentChange(page) {
        this.params.page_no = page
        this.GET_CouponsList()
      },

      /** 当选择项发生变化 */
      handleSelectionChange(val) {
        this.selectedData = val.map(item => item);
      },

      /** 搜索事件触发 */
      searchEvent(data) {
        this.params = {
          ...this.params,
          keyword: data
        }
        Object.keys(this.advancedForm).forEach(key => delete this.params[key])
        delete this.params.start_time
        delete this.params.end_time
        this.GET_CouponsList()
      },

      /** 搜索事件触发 */
      searchCoupon_type() {
        this.params = {
          ...this.params,
          coupon_type: this.searchCouponData
        }
        Object.keys(this.advancedForm).forEach(key => delete this.params[key])
        delete this.params.start_time
        delete this.params.end_time
        this.GET_CouponsList()
      },

      /** 高级搜索事件触发 */
      advancedSearchEvent() {
        this.params = this.MixinClone(this.params)
        const { coupon_time_limit } = this.advancedForm
        if (coupon_time_limit && coupon_time_limit[0]) {
          this.params.start_time = coupon_time_limit[0] / 1000
          this.params.end_time = coupon_time_limit[1] / 1000
        } else {
          delete this.params.start_time
          delete this.params.end_time
        }
        delete this.params.keyword
        this.GET_CouponsList()
      },

      GET_CouponsList() {
        this.loading = true
        API_coupon.getCouponsList(this.params).then(response => {
          this.loading = false
          this.pageData = {
            page_no: response.page_no,
            page_size: response.page_size,
            data_total: response.data_total
          }
          this.tableData = response.data
          /** 已经使用量 */
          this.tableData.forEach(key => {
            key.used_num = key.used_num || 0
          })
        })
      },

      /** 删除优惠券 */
      handleDeleteGoods(row) {
        this.$confirm('确认删除此优惠券, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          API_coupon.deleteCoupons(row.coupon_id, row).then(() => {
            this.GET_CouponsList()
            this.$message.success('删除优惠券成功！')
          })
        }).catch(() => {
          this.$message.info({ message: '已取消删除' })
        })
      },

      /** 结束优惠券 */
      handleEndCoupons(row) {
        this.$confirm('确认结束此优惠券活动, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          API_coupon.endCoupons(row.coupon_id).then(() => {
            this.GET_CouponsList()
            this.$message.success('结束优惠券成功！')
          })
        }).catch(() => {
          this.$message.info({ message: '已取消删除' })
        })
      },

      /** 修改*/
      handleEditCoupons(row) {
        this.couponModelShow = true
        this.currentcouponId = row.coupon_id
      },

      /** 新增优惠券*/
      handleAddCoupon() {
        this.couponModelShow = true
        this.currentcouponId = ''
      },

      /** 推送到用户*/
      handlePushToClient() {
        if (this.selectedData.length < 1) {
          this.$message.error('您未选中任何优惠券！')
        }
        //  else if (this.selectedData.length > 1) {
        //   this.$message.error('一次只能选择一张优惠券！')
        // }
        else {
          let useTime = null;
          if (this.selectedData[0].use_period) {
            useTime = this.selectedData[0].use_period
          } else {
            useTime = Math.ceil((this.selectedData[0].use_end_time - this.selectedData[0].use_start_time) / 86400 );
          }
          let sum = 0;
          let countPrice = 0;
          this.selectedData.forEach((item) => {
            sum += item.limit_num ? item.limit_num : 1;
            countPrice += item.coupon_price;
          })
          this.selectedPromos = {
            count: this.selectedData.length,
            pice: sum,
            count_price: countPrice
          };
          this.pushForm.content = `【门口淘】恭喜你获得${this.selectedPromos.count_price}元优惠券礼包，快来门口淘小程序使用吧~`;
          this.dialogPushShow = true;
        }
      },

      /** 确认推送给用户 */
      submitpushForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.btnLoading = true;
            let coupon_id = this.selectedData.map((item) => {
              return item.coupon_id
            });
            let params = {
              'content': this.pushForm.content,
              'coupon_id': coupon_id.toString(),
              'mobile': this.pushForm.mobile
            }
            API_coupon.batch_push(params).then((res) => {
              if (res.success) {
                this.$message.success(res.message);
                this.pushForm.mobile = '';
                this.dialogPushShow = false;
                this.btnLoading = false;
              } else {
                this.$message.warning(res.message);
                this.pushForm.mobile = '';
                this.dialogPushShow = false;
                this.btnLoading = false;
              }
            }).catch((err) => {
              this.$message.warning( err.message );
              this.btnLoading = false;
            })
          } else {
            console.log('error submit!!');
            return false;
          }
        })
      },

      /** 优惠券监听 */
      saveCoupon(target) {
        this.couponModelShow = false
        this.currentcouponId = ''
        target && this.GET_CouponsList()
      }
    }
  }
</script>

<style type="text/scss" lang="scss" scoped>

  /deep/ div.toolbar {
    height: 70px;
    padding: 20px 0;
  }

  /deep/ .el-table td:not(.is-left) {
    text-align: center;
  }

  .inner-toolbar {
    min-width: 910px;
    display: flex;
    width: 100%;
    justify-content: space-between;
  }

  .toolbar-search {
    margin-right: 10px;
  }

  .goods-image {
    width: 50px;
    height: 50px;
  }

  .choosedPromos{
    color: rgb(236, 18, 18);
  }
.toolbar-search{
  display: flex;
  flex-flow: row nowrap;
  .cityAddr{
    margin-right: 10px;
    font-size: 12px;
  }
}

</style>
